package com.qdsg.ysg.doctor.ui.activity.mine;

import android.annotation.SuppressLint;
import android.os.Build;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseActivity;
import com.qdsg.ysg.doctor.util.ToastUtil;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Description: 医院提供的签名设置H5页面
 * @Author: lzp
 * @CreateDate: 2022/5/11 10:31
 * @UpdateRemark: 更新说明
 */
public class SignatureActivity extends BaseActivity {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.webview)
    WebView webview;
    String url;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void initViews() {
        WebSettings settings = webview.getSettings();
        settings.setUseWideViewPort(true);// 设置此属性，可任意比例缩放
        //自适应屏幕
        settings.setJavaScriptEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setDomStorageEnabled(true); // 是否节点缓存
        settings.setDatabaseEnabled(true); // 是否数据缓存
        //支持缩放
        settings.setSupportZoom(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        settings.setAppCacheEnabled(true);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);//优先使用缓存
        }
        settings.setBlockNetworkImage(false);
        settings.setDefaultTextEncodingName("utf-8");//设置编码格式

        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (webview != null) {
                    if (newProgress == 100) {
                        progressBar.setVisibility(View.GONE);//加载完网页进度条消失
                    } else {
                        progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                        progressBar.setProgress(newProgress);//设置进度值
                    }
                }
                super.onProgressChanged(view, newProgress);
            }

        });

        webview.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //该方法在Build.VERSION_CODES.LOLLIPOP以前有效，从Build.VERSION_CODES.LOLLIPOP起，建议使用shouldOverrideUrlLoading(WebView, WebResourceRequest)} instead
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址），均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242
                if ("https://ysg.com/caSignature".equals(url)) {
                    setResult(RESULT_OK);
                    finish();
                    return true;
                } else if (url.contains("https://ysg.com/auth")) {
                    setResult(RESULT_OK);
                    finish();
                    return true;
                }
                return false;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if ("https://ysg.com/caSignature".equals(request.getUrl().toString())) {
                        setResult(RESULT_OK);
                        finish();
                        return true;
                    } else if (request.getUrl().toString().contains("https://ysg.com/auth?type=0")) {
                        finish();
                        return true;
                    } else if (request.getUrl().toString().contains("https://ysg.com/auth?type=1")) {
                        setResult(RESULT_OK);
                        finish();
                        return true;
                    }
//                    else if (request.getUrl().toString().contains("https://ysg.com/auth")) {
//                        setResult(RESULT_OK);
//                        finish();
//                        return true;
//                    }
                }
                return false;
            }
        });
        webview.loadUrl(url);
    }


    @Override
    protected void initData() {
        url = getIntent().getStringExtra("url");
        int type = getIntent().getIntExtra("type", 0);
        if (type == 1) {
            tvTitle.setText("");
        }
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_signature;
    }

    //设置返回键动作（防止按返回键直接退出程序)
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onResume() {
        webview.onResume();
        webview.resumeTimers();
        super.onResume();
    }

    @Override
    public void onPause() {
        webview.onPause();
        webview.pauseTimers();
        super.onPause();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (webview != null) {
            // 清理缓存
            webview.stopLoading();
            webview.onPause();
            webview.clearHistory();
            webview.clearCache(true);
            webview.clearFormData();
            webview.clearSslPreferences();
            WebStorage.getInstance().deleteAllData();
            webview.destroyDrawingCache();
            webview.removeAllViews();
            // 最后再去webView.destroy();
            webview.destroy();
            webview = null;
        }
    }

    @OnClick(R.id.btn_back)
    public void onViewClicked() {
        finish();
    }
}
